<template>
	<div class="animated bounceInDown sele_none">
		<el-row>
			<el-col :span="24">
				<div class="separate_page area1">
					<h3>商品排行 - TOP12</h3>
					<div id="goodsOrder" class="h100"></div>
				</div>
			</el-col>
		</el-row>
		<el-row :gutter="16">
			<el-col :span="7">
				<div class="separate_page area2">
					<div class="dflex_sb">
						<h3>访客排行</h3>
						<el-select size="small" style="width: 100px;" class="state_search" v-model="visit" @change="visitChange">
							<el-option v-for="item in stateOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
						</el-select>
					</div>
					<el-table
						height="400"
						v-loading="visitTableLoading"
						:data="visitTableDatas.filter(x => x.goods.state == visit || visit == '全部')"
						highlight-current-row
						class="margin_t_10 animated bounceInDown"
					>
						<el-table-column label="访客数" align="center">
							<template slot-scope="scope">
								<div class="dflex_c">
									<div v-if="scope.row.hot < 3" class="iconfont iconhuo margin_r_5"></div>
									<div>{{ scope.row.visit }}</div>
								</div>
							</template>
						</el-table-column>
						<el-table-column label="图片" align="center" width="80">
							<template slot-scope="scope">
								<use-carousel :width="70" :height="70" :imgs="scope.row.goods.imgs" :video="scope.row.goods.video"></use-carousel>
							</template>
						</el-table-column>
						<el-table-column label="名称" align="center" width="160">
							<template slot-scope="scope">
								<el-popover :open-delay="350" :close-delay="80" placement="right" trigger="hover" :content="scope.row.goods.name">
									<div slot="reference" class="ellipsis crpr">{{ scope.row.goods.name }}</div>
								</el-popover>
							</template>
						</el-table-column>
						<el-table-column property="goods.state" label="状态" align="center"></el-table-column>
						<div slot="empty"><el-empty description=" "></el-empty></div>
					</el-table>
				</div>
			</el-col>
			<el-col :span="7">
				<div class="separate_page area2">
					<div class="dflex_sb">
						<h3>浏览排行</h3>
						<el-select size="small" style="width: 100px;" class="state_search" v-model="browse" @change="browseChange">
							<el-option v-for="item in stateOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
						</el-select>
					</div>
					<el-table
						height="400"
						v-loading="browseTableLoading"
						:data="browseTableDatas.filter(x => x.goods.state == browse || browse == '全部')"
						highlight-current-row
						class="margin_t_10 animated bounceInDown"
					>
						<el-table-column label="浏览数" align="center">
							<template slot-scope="scope">
								<div class="dflex_c">
									<div v-if="scope.row.hot < 3" class="iconfont iconhuo margin_r_5"></div>
									<div>{{ scope.row.browse }}</div>
								</div>
							</template>
						</el-table-column>
						<el-table-column label="图片" align="center" width="80">
							<template slot-scope="scope">
								<use-carousel :width="70" :height="70" :imgs="scope.row.goods.imgs" :video="scope.row.goods.video"></use-carousel>
							</template>
						</el-table-column>
						<el-table-column label="名称" align="center" width="160">
							<template slot-scope="scope">
								<el-popover :open-delay="350" :close-delay="80" placement="right" trigger="hover" :content="scope.row.goods.name">
									<div slot="reference" class="ellipsis crpr">{{ scope.row.goods.name }}</div>
								</el-popover>
							</template>
						</el-table-column>
						<el-table-column property="goods.state" label="状态" align="center"></el-table-column>
						<div slot="empty"><el-empty description=" "></el-empty></div>
					</el-table>
				</div>
			</el-col>
			<el-col :span="10">
				<div class="separate_page margin_b_0 area2">
					<h3>商品类型分布</h3>
					<div id="goodsType" class="h100 animated bounceInDown"></div>
				</div>
			</el-col>
		</el-row>
		<el-backtop target="uni-page-body"></el-backtop>
	</div>
</template>

<script>
import echarts from 'echarts';
export default {
	data() {
		return {
			goodsOrderDom: null,
			goodsOrderOption: [],
			visitTableLoading: false,
			visitTableDatas: [],
			browseTableLoading: false,
			browseTableDatas: [],
			stateOptions: [
				{
					value: '全部',
					label: '全部'
				},
				{
					value: '待审核',
					label: '待审核'
				},
				{
					value: '销售中',
					label: '销售中'
				},
				{
					value: '已下架',
					label: '已下架'
				}
			],
			visit: '全部',
			browse: '全部',
			goodsTypeDom: null,
			goodsTypeOption: []
		};
	},
	methods: {
		async goodsOrderData() {
			this.goodsOrderDom.showLoading({
				text: '加载中 · · ·',
				color: '#ff6a6c',
				textColor: '#000',
				maskColor: 'rgba(255, 255, 255, 1)'
			});

			const res1 = this.$db['wmzmall-order-detail, wmzmall-goods']
				.collection()
				.action('base-where-action')
				.where({
					shop_id:uni.getStorageSync('wmzadmin_user_shop_id')
				})
				.groupBy('goods_id')
				.groupField('count(*) as order_cnt')
				.orderBy('order_cnt desc')
				.limit(12)
				.get();

			const res2 = this.$db['wmzmall-order-detail, wmzmall-goods, wmzmall-order']
				.collection()
				.action('base-where-action')
				.where({
					shop_id:uni.getStorageSync('wmzadmin_user_shop_id'),
					'order_id.order_pay_state': '已付款'
				})
				.groupBy('goods_id, order_id')
				.groupField('count(*) as cnt')
				.orderBy('cnt desc')
				.limit(12)
				.get();

			let res = {
				code: 0,
				datas: []
			};

			await Promise.all([res1, res2])
				.then(resData => {
					if (resData[0].result.data && resData[0].result.data.length > 0) {
						if (resData[1].result.data && resData[1].result.data.length > 0) {
							let payDatas = [];
							resData[0].result.data.forEach(x => {
								if (x.goods_id.length > 0) {
									payDatas = resData[1].result.data.filter(o => o.goods_id.length > 0 && x.goods_id[0]._id == o.goods_id[0]._id).map(o => o.cnt);
									x.pay_cnt = 0;
									if (payDatas.length > 0) {
										x.pay_cnt = payDatas.reduce((p, c) => {
											return p + c;
										});
									}
								}
							});
						}
					}

					resData[0].result.data.forEach(x => {
						if (x.goods_id.length > 0) {
							res.datas.push({
								name: x.goods_id[0].name.substr(0, 7),
								order_cnt: x.order_cnt,
								pay_cnt: x.pay_cnt
							});
						}
					});
				})
				.catch(err => {
					this.goodsOrderDom.hideLoading();
				});

			this.goodsOrderDom.hideLoading();

			this.goodsOrderOption.xAxis.data = [];
			this.goodsOrderOption.series[0].data = [];
			this.goodsOrderOption.series[1].data = [];

			res.datas.forEach(x => {
				this.goodsOrderOption.xAxis.data.push(x.name);

				this.goodsOrderOption.series[0].data.push({
					value: x.order_cnt || 0
				});

				this.goodsOrderOption.series[1].data.push({
					value: x.pay_cnt || 0
				});
			});

			this.goodsOrderDom.setOption(this.goodsOrderOption);
		},
		goodsOrderCharts(callback) {
			this.goodsOrderDom = this.$echarts.init(document.getElementById('goodsOrder'));

			this.goodsOrderOption = {
				backgroundColor: '#fff',
				grid: {
					top: '50px',
					bottom: '60px',
					left: '30px',
					right: '30px'
				},
				tooltip: {
					trigger: 'axis',
					axisPointer: {
						type: 'shadow',
						label: {
							show: true
						}
					},
					formatter: ' {a0}: {c0}   \n {a1}: {c1}   '
				},
				legend: {
					data: ['订单数', '支付数'],
					top: '0%',
					textStyle: {
						color: '#000'
					}
				},
				xAxis: {
					axisLine: {
						show: false //隐藏X轴轴线
					},
					axisTick: {
						show: false //隐藏X轴刻度
					},
					axisLabel: {
						show: true,
						textStyle: {
							color: '#000' //X轴文字颜色
						}
					},
					data: []
				},
				yAxis: [
					{
						nameTextStyle: {
							color: 'rgba(0,0,0,0.5)',
							align: 'left'
						},
						axisLine: {
							show: false
						},
						splitLine: {
							show: true,
							lineStyle: {
								color: 'rgba(0, 0, 0, 0.1)'
							}
						},
						axisTick: {
							show: false
						},
						splitArea: {
							show: true,
							areaStyle: {
								color: 'rgba(0, 0, 0, 0)'
							}
						}
					}
				],
				series: [
					{
						name: '订单数',
						type: 'bar',
						barWidth: 40,
						itemStyle: {
							normal: {
								//线性渐变，前4个参数分别是x0,y0,x2,y2(范围0~1);相当于图形包围盒中的百分比。如果最后一个参数是‘true’，则该四个值是绝对像素位置。
								color: new echarts.graphic.LinearGradient(
									0,
									0,
									0,
									1,
									[
										{
											offset: 0,
											color: 'rgba(255, 106, 108, 0.9)'
										},
										{
											offset: 1,
											color: 'rgba(255, 106, 108, 0.1)'
										}
									],
									false
								),

								shadowColor: 'rgba(255, 106, 108, 0)', //阴影颜色
								shadowBlur: 20 //shadowBlur设图形阴影的模糊大小。配合shadowColor,shadowOffsetX/Y, 设置图形的阴影效果。
							}
						},
						data: []
					},
					{
						name: '支付数',
						type: 'bar',
						barWidth: 40,
						itemStyle: {
							normal: {
								//线性渐变，前4个参数分别是x0,y0,x2,y2(范围0~1);相当于图形包围盒中的百分比。如果最后一个参数是‘true’，则该四个值是绝对像素位置。
								color: new echarts.graphic.LinearGradient(
									0,
									0,
									0,
									1,
									[
										{
											offset: 0,
											color: 'rgba(255, 106, 108, 0.9)'
										},
										{
											offset: 1,
											color: 'rgba(255, 106, 108, 0.1)'
										}
									],
									false
								),

								shadowColor: 'rgba(255, 106, 108, 0)', //阴影颜色
								shadowBlur: 20 //shadowBlur设图形阴影的模糊大小。配合shadowColor,shadowOffsetX/Y, 设置图形的阴影效果。
							}
						},
						data: []
					}
				]
			};

			window.addEventListener('resize', () => {
				this.goodsOrderDom.resize();
			});

			if (typeof callback === 'function') {
				callback();
			}
		},
		async getVisit() {
			this.visitTableLoading = true;
			const res1 = this.$db['wmzmall-goods-history, wmzmall-goods']
				.collection()
				.action('base-where-action')
				.where({
					shop_id:uni.getStorageSync('wmzadmin_user_shop_id')
				})
				.groupBy('goods')
				.groupField('count(*) as visit')
				.orderBy('visit desc')
				.get();

			const resData = await Promise.all([res1]);

			this.visitTableLoading = false;

			let res = {
				code: 0,
				datas: []
			};

			resData[0].result.data.forEach((x, idx) => {
				if (x.goods.length > 0) {
					res.datas.push({
						goods: x.goods[0],
						visit: x.visit,
						hot: idx
					});
				}
			});

			if (res.datas.length > 0) {
				res.code = 200;
			}

			if (res.code == 200) {
				this.visitTableDatas = res.datas;
			}
		},
		async getBrowse() {
			this.browseTableLoading = true;
			const res1 = this.$db['wmzmall-goods-history, wmzmall-goods']
				.collection()
				.action('base-where-action')
				.where({
					shop_id:uni.getStorageSync('wmzadmin_user_shop_id')
				})
				.groupBy('goods')
				.groupField('sum(visit_cnt) as browse')
				.orderBy('browse desc')
				.get();

			const resData = await Promise.all([res1]);

			this.browseTableLoading = false;

			let res = {
				code: 0,
				datas: []
			};

			resData[0].result.data.forEach((x, idx) => {
				if (x.goods.length > 0) {
					res.datas.push({
						goods: x.goods[0],
						browse: x.browse,
						hot: idx
					});
				}
			});

			if (res.datas.length > 0) {
				res.code = 200;
			}

			if (res.code == 200) {
				this.browseTableDatas = res.datas;
			}
		},
		visitChange() {
			uni.setStorage({
				key: '__visitCutSta' + this.$route.path,
				data: this.visit
			});
		},
		browseChange() {
			uni.setStorage({
				key: '__browseCutSta' + this.$route.path,
				data: this.browse
			});
		},
		async goodsTypeData() {
			this.goodsTypeDom.showLoading({
				text: '加载中 · · ·',
				color: '#ff6a6c',
				textColor: '#000',
				maskColor: 'rgba(255, 255, 255, 1)'
			});

			const res1 = this.$db['wmzmall-goods']
				.collection()
				.action('base-where-action')
				.where({
					shop_id:uni.getStorageSync('wmzadmin_user_shop_id')
				})
				.groupBy('state')
				.groupField('count(*) as cnt')
				.get();

			const $ = this.$db.$cmd.aggregate;
			const res2 = this.$db['wmzmall-goods, wmzmall-goods-category']
				.collection()
				.action('base-where-action')
				.aggregate()
				.match({
					shop_id:uni.getStorageSync('wmzadmin_user_shop_id')
				})
				.group({
					_id: '$cid',
					cnt: $.sum(1)
				})
				.end();

			const resData = await Promise.all([res1, res2]);

			this.goodsTypeDom.hideLoading();

			let state = {
				code: 0,
				datas: []
			};

			let category = {
				code: 0,
				datas: []
			};

			resData[0].result.data.forEach(x => {
				state.datas.push({
					cnt: x.cnt,
					state: x.state
				});
			});

			resData[1].result.data.forEach(x => {
				category.datas.push({
					cnt: x.cnt,
					name: x._id[0] && x._id[0].name
				});
			});

			if (state.datas.length > 0) {
				state.code = 200;
			}

			if (state.code == 200) {
				state.datas.forEach(x => {
					this.goodsTypeOption.series[0].data.push({
						value: x.cnt,
						name: x.state
					});
				});
			}

			if (category.datas.length > 0) {
				category.code = 200;
			}

			if (category.code == 200) {
				category.datas.forEach(x => {
					this.goodsTypeOption.series[1].data.push({
						value: x.cnt,
						name: x.name
					});
				});
			}
			this.goodsTypeDom.setOption(this.goodsTypeOption);
		},
		goodsTypeCharts(callback) {
			this.goodsTypeDom = this.$echarts.init(document.getElementById('goodsType'));

			this.goodsTypeOption = {
				backgroundColor: '#fff',
				color: [
					'#2ec7c9',
					'#b6a2de',
					'#5ab1ef',
					'#ffb980',
					'#d87a80',
					'#8d98b3',
					'#FFEA01',
					'#B8D07C',
					'#fca4bb',
					'#dc69aa',
					'#07a2a4',
					'#9a7fd1',
					'#588dd5',
					'#f5994e',
					'#c05050',
					'#59678c',
					'#c9ab00',
					'#7eb00a',
					'#6f5553',
					'#c14089'
				],
				tooltip: {
					trigger: 'item',
					formatter: ' {a}   \n {b}: {c}   '
				},
				series: [
					{
						name: '商品状态',
						type: 'pie',
						radius: ['0', '36%'],
						itemStyle: {
							normal: {
								borderColor: 'rgba(0, 0, 0, 0)'
							}
						},
						label: {
							position: 'inside'
						},
						data: []
					},
					{
						name: '商品分类',
						type: 'pie',
						radius: ['45%', '55%'],
						labelLine: {
							length2: 90,
							lineStyle: {
								color: 'rgba(0, 0, 0, 0.1)'
							}
						},
						label: {
							formatter: params => {
								return '{icon|●}{name|' + params.name + '}{value|' + params.value + '}';
							},
							padding: [0, -70, 16, -70],
							rich: {
								color: '#333',
								icon: {
									fontSize: 16
								},
								name: {
									fontSize: 14,
									padding: [0, 5, 0, 5],
									color: '#666666'
								},
								percent: {
									color: '#333',
									padding: [0, 5, 0, 0]
								},
								value: {
									fontSize: 16,
									color: '#333333'
								}
							}
						},
						data: []
					}
				]
			};

			window.addEventListener('resize', () => {
				this.goodsTypeDom.resize();
			});

			if (typeof callback === 'function') {
				callback();
			}
		}
	},
	created() {
		this.getVisit();
		this.visit = uni.getStorageSync('__visitCutSta' + this.$route.path) || '全部';
		this.getBrowse();
		this.browse = uni.getStorageSync('__browseCutSta' + this.$route.path) || '全部';
	},
	mounted() {
		this.goodsOrderCharts(() => {
			this.goodsOrderData();
		});

		this.goodsTypeCharts(() => {
			this.goodsTypeData();
		});

		this.$nextTick(() => {
			this.$api.scrollOnStorage('uni-page-body', this.$route.path);
		});

		this.$nextTick(() => {
			this.$api.scrollToStorage('uni-page-body', this.$route.path);
		});
	}
};
</script>

<style>
.area1,
.area2,
.area3 {
	height: 500px;
}

.ellipsis {
	width: 150px;
}

.area2 .iconhuo {
	color: rgba(255, 106, 108, 1);
}
</style>
